<template>
  <BasicVxeModal
    v-bind="$attrs"
    :width="600"
    :height="400"
    :title="t('custom.换段记录更新')"
    :show-maximize="false"
    :show-footer="false"
    @register="registerModal"
  >
    <div class="modal-container">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item :label="t('custom.段名')" prop="name">
          <el-select v-model="form.name" :placeholder="t('custom.请选择')">
            <el-option label="整车" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('custom.机台选择')" prop="machineDocumentId">
          <el-select
            v-model="form.machineDocumentId"
            :placeholder="t('custom.请选择')"
            :disabled="disabledFlag"
          >
            <el-option
              :label="item.machineName"
              :value="item.id"
              v-for="(item, index) in machineOptions"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('custom.粗纱换段时间')" prop="changeTime">
          <el-date-picker
            v-model="form.changeTime"
            type="datetime"
            :placeholder="t('custom.请选择')"
            format="YYYY/MM/DD HH:mm"
            time-format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="t('custom.粗纱定量') + '(g/km)'">
          <el-input-number v-model="form.csWeightPerLength" controls-position="right" />
        </el-form-item>
        <el-form-item :label="t('custom.粗纱原始长度') + '(m)'" prop="csOriginalLength">
          <el-input-number v-model="form.csOriginalLength" controls-position="right" />
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item class="btn-item">
          <el-button :loading="btnLoading" type="primary" @click="submitForm(formRef)">
            {{ disabledFlag ? t('custom.修改') : t('custom.新增') }}
          </el-button>
          <el-button type="primary">关闭</el-button>
        </el-form-item>
      </el-form>
    </div>
  </BasicVxeModal>
</template>

<script setup lang="ts">
  import { useVxeModalInner } from '@/components/ui/vxe-modal'
  import dayjs from 'dayjs'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { postHuanDuanJiLuChaRu, putXiuGaiHuanDuanJiLuChaRu } from '@/api/shengChanJianShi'

  const { t } = useI18n()
  interface FormData {
    name: number | string
    machineName: string
    machineDocumentId: string
    changeTime: string
    csWeightPerLength: number | string | undefined
    csOriginalLength: number | string | undefined
  }
  const formRef = ref<FormInstance>()
  const form = reactive<FormData>({
    name: 1,
    machineDocumentId: '',
    machineName: '',
    changeTime: dayjs().format('YYYY-MM-DD HH:mm'),
    csWeightPerLength: undefined,
    csOriginalLength: undefined
  })
  const rules = reactive<FormRules<FormData>>({
    name: [{ required: true, message: t('custom.请选择') + t('custom.段名'), trigger: 'change' }],
    machineDocumentId: [
      { required: true, message: t('custom.请选择') + t('custom.机台'), trigger: 'change' }
    ],
    changeTime: [
      { required: true, message: t('custom.请选择') + t('custom.粗纱换段时间'), trigger: 'change' }
    ],
    csOriginalLength: [
      { required: true, message: t('custom.请输入') + t('custom.粗纱原始长度'), trigger: 'blur' }
    ]
  })

  const machineOptions = ref<any>([])
  const disabledFlag = ref(false)
  const [registerModal, { closeModal }] = useVxeModalInner(async (_data) => {
    // setModalProps({ loading: true })
    console.log(_data)
    machineOptions.value = _data.optionList
    if (_data.row.machineNo) {
      disabledFlag.value = true
      form.changeTime =
        _data.row.changeTime == '/'
          ? dayjs().format('YYYY-MM-DD HH:mm')
          : dayjs(_data.row.changeTime).format('YYYY-MM-DD HH:mm')
      form.machineDocumentId = _data.optionList.filter(
        (item) => item.machineName == _data.row.machineName
      )[0].id
      form.csWeightPerLength = _data.row.fixRationCs
      form.csOriginalLength = _data.row.fixLengthCs
    }
  })

  const btnLoading = ref(false)
  const emit = defineEmits(['update'])
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        btnLoading.value = true
        disabledFlag.value ? operateEdit() : operateAdd()
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  const operateAdd = () => {
    postHuanDuanJiLuChaRu(form)
      .then(() => {
        btnLoading.value = false
        emit('update')
        closeModal()
        ElMessage.success(t('custom.保存成功'))
      })
      .catch(() => {
        btnLoading.value = false
      })
  }
  const operateEdit = () => {
    putXiuGaiHuanDuanJiLuChaRu(form)
      .then(() => {
        btnLoading.value = false
        emit('update')
        closeModal()
        ElMessage.success(t('custom.修改成功'))
      })
      .catch(() => {
        btnLoading.value = false
      })
  }
</script>

<style lang="scss" scoped>
  :deep(.el-input-number) {
    width: 100%;

    input {
      text-align: left;
    }
  }

  .modal-container {
    padding-top: 10px;
  }

  .el-divider {
    margin: 42px 0 11px 0;
  }

  :deep(.btn-item .el-form-item__content) {
    justify-content: end;
  }

  .el-form-item {
    margin: 0 50px 18px;
  }

  .btn-item {
    text-align: right;
    margin-bottom: 8px;
  }
</style>
